package logic

import (
	"context"
	"database/sql"

	"googee/common/tool"
	"googee/service/sms/model"
	"googee/service/sms/rpc/internal/svc"
	"googee/service/sms/rpc/types/sms"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type SendShortMessageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendShortMessageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendShortMessageLogic {
	return &SendShortMessageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 发送短信
func (l *SendShortMessageLogic) SendShortMessage(in *sms.SendSmsRequest) (*sms.SendSmsResponse, error) {
	phone := in.GetPhone()
	userId := in.GetId()
	content := in.GetContent()

	if phone == "" || !tool.VerifyMobileFormat(phone) {
		return nil, status.Error(codes.InvalidArgument, "parameter password is empty or phone is not a valid phone number")
	}

	//查看一分钟之前是否已经发送过验证码类的短信
	smss, _ := l.svcCtx.SmsModel.FindLastVerifySmsByUserId(l.ctx, userId, l.svcCtx.Config.VerifySMS.Interval)
	if len(smss) > 0 {
		return nil, status.Error(codes.AlreadyExists, " verify sms already exist")
	}

	var smsmodel model.Sms
	smsmodel.Content = sql.NullString{String: content, Valid: true}
	smsmodel.Phone = sql.NullString{String: phone, Valid: true}
	smsmodel.UserId = sql.NullInt64{Int64: userId, Valid: true}
	smsmodel.Typ = int64(in.Typ)
	smsmodel.Valid = 1

	l.svcCtx.SmsModel.Insert(l.ctx, &smsmodel)

	return &sms.SendSmsResponse{}, nil
}
